package com.craftplay.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.craftplay.common.ServerResponse;
import com.craftplay.model.Collection;
import com.craftplay.model.*;
import com.craftplay.service.*;
import com.craftplay.util.AliMsgSendUtil;
import com.craftplay.util.ToolUntils;
import com.craftplay.util.UserAgentUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/play/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private EnrollService enrollService;

    @Autowired
    private MomentService momentService;

    @Autowired
    private OfferService offerService;

    @Autowired
    HostHolder hostHolder;

    @Autowired
    RecommendService recommendService;

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private FocusService focusService;

    @Autowired
    private LoveService loveService;

    @Autowired
    private CollectionService collectionService;

    @Autowired
    private BehaveService behaveService;


    @RequestMapping(method = RequestMethod.GET, value = "/info")
    @ResponseBody
    public ServerResponse<User> userInfo(Integer userId, HttpServletRequest request) {
        User user;
        if (userId == null) {
            user = hostHolder.getUser();
        } else {
            user = userService.selectUserById(userId);
        }
        if (user == null) return ServerResponse.createByErrorMessage("获取用户信息失败！");
        if (UserAgentUtil.isWechat(request) || !user.getUserId().equals(-1)) {
            try {
                WxMpUser wxMpUser = this.wxMpService.getUserService().userInfo(user.getOpenId(), null);
                userService.checkUserInfo(wxMpUser);
                user = userService.selectByOpenId(wxMpUser.getOpenId());
                int focusNum = focusService.myFocusUserNum(user.getUserId());
                int fanNum = focusService.focusMyUserNum(user.getUserId());
                int collectNum = collectionService.focusMyUserNum(user.getUserId());
                user.setFocusNum(focusNum);
                user.setCollectionNum(collectNum);
                user.setFansNum(fanNum);
                hostHolder.setUser(user);
            } catch (WxErrorException e) {
                System.out.println(String.format("wxMpService错误", e));
                e.printStackTrace();
            }
        } else {
            //匿名用户，非微信端用户
            hostHolder.setUser(user);
        }
        return ServerResponse.createBySuccess(user);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/infobyid")
    @ResponseBody
    public ServerResponse<List<User>> getUserIntro(@RequestParam("id") int[] id) {
        List<User> userList = new ArrayList<User>();
        User nowUser = hostHolder.getUser();
        boolean isSuccess = false;
        for (int item : id) {
            User user = userService.selectUserById(item);
            if (user != null) {
                int focusNum = focusService.myFocusUserNum(item);
                int fanNum = focusService.focusMyUserNum(item);
                int collectNum = collectionService.focusMyUserNum(item);
                user.setFocus(focusService.isFocusUser(nowUser.getUserId(), item));
                user.setFocusNum(focusNum);
                user.setCollectionNum(collectNum);
                user.setFansNum(fanNum);
                userList.add(user);
                isSuccess = true;
            } else {
                isSuccess = false;
            }
        }

        if (isSuccess == true) {
            return ServerResponse.createBySuccess(userList);
        } else {
            return ServerResponse.createByErrorMessage("获取用户信息失败！");
        }
    }


    @RequestMapping(method = RequestMethod.POST, value = "/upbasic")
    @ResponseBody
    public ServerResponse<String> updateTelAndSign(@RequestBody User user) {
        if (user != null && hostHolder.getUser() != null) {
            User hostUser = hostHolder.getUser();
            if (hostUser.getUserId() == -1) {
                return ServerResponse.createBySuccessMessage("匿名用户不允许操作");
            }
            String feature = user.getFeature();
            String telNumber = user.getTel();
            String openId = hostHolder.getUser().getOpenId();
            String nickname = user.getNickname();
            if (nickname == null) {
                nickname = hostHolder.getUser().getNickname();
            }
            if (userService.updateUserInfo(feature, telNumber, openId, nickname, hostUser.getUserType()) > 0) {
                return ServerResponse.createBySuccessMessage("更新成功");
            } else {
                return ServerResponse.createByErrorMessage("更新失败！");
            }
        }
        return ServerResponse.createByErrorMessage("更新失败！");
    }

    @RequestMapping(method = RequestMethod.POST, value = "/upintro")
    @ResponseBody
    public ServerResponse<User> updateIntro(@RequestBody User user) {
        if (user != null && hostHolder.getUser() != null) {
            User hostUser = hostHolder.getUser();
            if (hostUser.getUserId() == -1) {
                return ServerResponse.createBySuccessMessage("匿名用户不允许操作");
            }
            String intro = user.getIntro();
            String introImgUrl = user.getIntroImgUrl();
            String openId = hostHolder.getUser().getOpenId();
            if (userService.updateIntro(intro, introImgUrl, openId) > 0) {
                return ServerResponse.createBySuccessMessage("更新成功");
            } else {
                return ServerResponse.createByErrorMessage("更新失败！");
            }
        }
        return ServerResponse.createByErrorMessage("更新失败！");
    }

    @RequestMapping(method = RequestMethod.POST, value = "/addplace")
    @ResponseBody
    public ServerResponse<String> addPlace(@RequestBody Place place) {
        if (place != null && hostHolder.getUser() != null) {
            User hostUser = hostHolder.getUser();
            if (hostUser.getUserId() == -1) {
                return ServerResponse.createBySuccessMessage("匿名用户不允许操作");
            }
            place.setUserId(hostHolder.getUser().getUserId());
            if (userService.addPlace(place) > 0) {
                return ServerResponse.createBySuccessMessage("添加地点成功");
            } else {
                return ServerResponse.createByErrorMessage("添加地点失败！");
            }
        }
        return ServerResponse.createByErrorMessage("添加地点失败！");
    }

    @RequestMapping(method = RequestMethod.GET, value = "/allplace")
    @ResponseBody
    public ServerResponse<List<Place>> findAllPlace(Integer userId) {
        //if (hostHolder.getUser() != null) {
        //int userId = hostHolder.getUser().getUserId();
        List<Place> placeList = userService.findAllPlace(userId);
        if (placeList != null) {
            return ServerResponse.createBySuccess(placeList);
        } else {
            return ServerResponse.createByErrorMessage("查找失败！");
        }
        //}
        //return ServerResponse.createByErrorMessage("查找失败！");
    }

    @RequestMapping(method = RequestMethod.GET, value = "/remplace")
    @ResponseBody
    public ServerResponse<String> removePlace(@RequestParam("id") int id) {
        if (hostHolder.getUser() != null) {
            User hostUser = hostHolder.getUser();
            if (hostUser.getUserId() == -1) {
                return ServerResponse.createBySuccessMessage("匿名用户不允许操作");
            }
            if (userService.deletePlace(id) > 0) {
                return ServerResponse.createBySuccessMessage("删除成功");
            } else {
                return ServerResponse.createByErrorMessage("删除失败！");
            }
        }
        return ServerResponse.createByErrorMessage("删除失败！");
    }


    @RequestMapping(method = RequestMethod.POST, value = "/upplace")
    @ResponseBody
    public ServerResponse<String> updatePlace(@RequestBody Place place) {
        if (place != null && hostHolder.getUser() != null) {
            User hostUser = hostHolder.getUser();
            if (hostUser.getUserId() == -1) {
                return ServerResponse.createBySuccessMessage("匿名用户不允许操作");
            }
            int id = place.getId();
            String name = place.getName();
            String address = place.getAddress();
            String imgUrl = place.getImgUrl();
            if (userService.updatePlaceInfo(id, name, address, imgUrl) > 0) {
                return ServerResponse.createBySuccessMessage("更新成功");
            } else {
                return ServerResponse.createByErrorMessage("更新失败！");
            }
        }
        return ServerResponse.createByErrorMessage("更新失败！");
    }


    @RequestMapping(method = RequestMethod.GET, value = "/userjoin")
    @ResponseBody
    public ServerResponse<Set<Unit>> userJoin(Integer id) {

        List<Enroll> enrollList = enrollService.listAllPassedByActorId(id);
        List<Offer> offerList = offerService.listAllPassedByActorId(id);
        Set<Unit> set = new HashSet<Unit>();

        for (Enroll enroll : enrollList) {
            //joinList.add(enroll);
            set.add(momentService.oneMomentDetail(enroll.getUnitId()));
        }
        for (Offer offer : offerList) {
            set.add(momentService.oneMomentDetail(offer.getUnitId()));
        }

        if (set != null) {
            return ServerResponse.createBySuccess(set);
        } else {
            return ServerResponse.createByErrorMessage("获取列表失败！");
        }
    }


    @RequestMapping(method = RequestMethod.GET, value = "/userreq")
    @ResponseBody
    public ServerResponse<Set<Unit>> userReq(Integer id) {

        List<Enroll> enrollList = enrollService.listAllReqEnrollByActorId(id);
        List<Offer> offerList = offerService.listAllReqOfferByActorId(id);
        Set<Unit> set = new HashSet<Unit>();

        if (enrollList != null) {
            for (Enroll enroll : enrollList) {
                //joinList.add(enroll);
                Unit unit = momentService.oneMomentDetail(enroll.getUnitId());
                User user = userService.selectUserById(unit.getUserId());
                unit.setHeadImgUrl(user.getHeadUrl());
                unit.setUserName(user.getNickname());
                unit.setSex(user.getSex());
                set.add(unit);
            }
        }

        if (offerList != null) {
            for (Offer offer : offerList) {
                Unit unit = momentService.oneMomentDetail(offer.getUnitId());
                User user = userService.selectUserById(unit.getUserId());
                unit.setHeadImgUrl(user.getHeadUrl());
                unit.setUserName(user.getNickname());
                unit.setSex(user.getSex());
                set.add(unit);
            }
        }

        if (set != null) {
            return ServerResponse.createBySuccess(set);
        } else {
            return ServerResponse.createByErrorMessage("获取列表失败！");
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/recommender")
    @ResponseBody
    public ServerResponse<User> findRecomender() {
        User user = hostHolder.getUser();
        if (user != null) {
            String openId = user.getOpenId();
            Recommend recommend = recommendService.selectByOpenId(openId);
            if (recommend != null) {
                int recommendUserId = recommend.getUserId();
                User recommendUser = userService.selectUserById(recommendUserId);
                return ServerResponse.createBySuccess(recommendUser);
            } else {
                return ServerResponse.createByErrorMessage("暂无推荐人");
            }
        } else {
            return ServerResponse.createByErrorMessage("获取用户信息失败！");
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/rec_num")
    @ResponseBody
    public ServerResponse<List<User>> recommendNum() {
        User user = hostHolder.getUser();
        User currentUser = null;
        if (user != null) {
            int userId = user.getUserId();
            List<Recommend> recommendList = recommendService.selectByUserId(userId);
            List<User> userList = new ArrayList<User>();


            for (Recommend recommend : recommendList) {
                String oepnId = recommend.getOpenId();
                currentUser = userService.selectByOpenId(oepnId);
                userList.add(currentUser);
            }
            return ServerResponse.createBySuccess(userList);
        }
        return ServerResponse.createByErrorMessage("获取用户信息失败！");
    }


    @RequestMapping(method = RequestMethod.POST, value = "/sendSMS")
    @ResponseBody
    public ServerResponse<String> sendSMS(HttpServletRequest request, @RequestBody User userTel) {
        String tel = userTel.getTel();
        if (ToolUntils.isPhone(tel)) {
            //创建session对象
            HttpSession session = request.getSession();
            if (session != null) {
                //同一用户60秒请求一次
                if (session.getAttribute("sendTime") != null) {
                    long sendTime = (long) session.getAttribute("sendTime");
                    long serverTime = new Date().getTime();
                    if (serverTime - sendTime < 60000) {
                        return ServerResponse.createBySuccess("请求频繁请稍后");
                    }
                }
            }

            //短信接口
            int verificationCode = (int) ((Math.random() * 9 + 1) * 1000);
            session.setAttribute("verificationCode", verificationCode);
            session.setAttribute("tel", tel);
            session.setAttribute("sendTime", new Date().getTime());
            JSONObject json = new JSONObject().fluentPut("code", verificationCode);
            try {
                AliMsgSendUtil.sendSms(tel, "SMS_144240059", json);
                return ServerResponse.createBySuccess("发送成功");
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }

        return ServerResponse.createByErrorMessage("手机号码有误！");
    }


    @RequestMapping(method = RequestMethod.GET, value = "/validationSMS")
    @ResponseBody
    public ServerResponse<String> validationSMS(HttpServletRequest request, String verificationCode) {
        //得到session对象
        HttpSession session = request.getSession(false);
        if (session == null) {
            //没有登录成功，跳转到登录页面
            return ServerResponse.createByErrorMessage("未查到信息请重新验证！");
        }

        int serverCode = (int) session.getAttribute("verificationCode");
        String tel = (String) session.getAttribute("tel");
        long sendTime = (long) session.getAttribute("sendTime");
        long serverTime = new Date().getTime();
        if (NumberUtils.toInt(verificationCode) == serverCode) {
/*            if (serverTime-sendTime>50000){
                return ServerResponse.createByErrorMessage("验证码过期");
            }*/
            //根据userId更新手机号码
            User user = hostHolder.getUser();
            if (user == null) {
                return ServerResponse.createByErrorMessage("获取用户信息失败！");
            }
            user.setTel(tel);
            userService.updateByPrimaryKey(user);
            return ServerResponse.createBySuccess("验证成功");
        }
        return ServerResponse.createByErrorMessage("验证错误");


    }

    /**
     * 关注
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/focusUser")
    @ResponseBody
    public ServerResponse<String> focusUser(@RequestBody Focus focus) {
        User user = hostHolder.getUser();
        if (user != null) {
            User hostUser = hostHolder.getUser();
            if (hostUser.getUserId() == -1) {
                return ServerResponse.createBySuccessMessage("匿名用户不允许操作");
            }
            if (focus.getFocusUserId() == -1) {
                return ServerResponse.createByErrorMessage("不能关注匿名用户！");
            }
            User focusUser = userService.selectUserById(focus.getFocusUserId());
            if (focusUser == null) {
                return ServerResponse.createByErrorMessage("关注用户不存在！");
            }
            int i = focusService.focusUser(user.getUserId(), focus.getFocusUserId());
            if (i > 0) {
                return ServerResponse.createBySuccessMessage("关注成功");
            }
        }
        return ServerResponse.createByErrorMessage("获取用户信息失败！");
    }


    /**
     * 取消关注
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/unFocusUser")
    @ResponseBody
    public ServerResponse<String> unFocusUser(@RequestBody Focus focus) {
        User user = hostHolder.getUser();
        if (user != null) {
            User hostUser = hostHolder.getUser();
            if (hostUser.getUserId() == -1) {
                return ServerResponse.createBySuccessMessage("匿名用户不允许操作");
            }
            int i = focusService.unFocusUser(user.getUserId(), focus.getFocusUserId());
            if (i > 0) {
                return ServerResponse.createBySuccessMessage("取消关注成功");
            }
        }
        return ServerResponse.createByErrorMessage("取消关注失败！");
    }

    /**
     * 我的关注
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/myFocusUser")
    @ResponseBody
    public ServerResponse<List<User>> myFocusUser(@RequestParam("userId") int userId) {
        List<User> userList = new ArrayList<>();
        List<Focus> foci = focusService.myFocusUser(userId);
        for (Focus focus : foci) {
            User user1 = userService.selectUserById(focus.getFocusUserId());
            if (user1 != null) {
                user1.setTel(null);
                userList.add(user1);
            }
        }
        return ServerResponse.createBySuccess(userList);
    }


    /**
     * 我的粉丝
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/focusMyUser")
    @ResponseBody
    public ServerResponse<List<User>> focusMyUser(@RequestParam("userId") int userId) {
        List<User> userList = new ArrayList<>();
        List<Focus> foci = focusService.focusMyUser(userId);
        for (Focus focus : foci) {
            User user1 = userService.selectUserById(focus.getUserId());
            user1.setTel(null);
            userList.add(user1);
        }
        return ServerResponse.createBySuccess(userList);
    }


    /**
     * 新增喜欢
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/addLove")
    @ResponseBody
    public ServerResponse<String> myLove(@RequestBody Love myLove) {
        User user = hostHolder.getUser();
        User hostUser = hostHolder.getUser();
        if (hostUser.getUserId() == -1) {
            return ServerResponse.createBySuccessMessage("匿名用户不允许操作");
        }
        if (user != null) {
            Love love = new Love();
            love.setUnitId(myLove.getUnitId());
            love.setUserId(user.getUserId());
            love.setLoveTime(new Date());
            int i = loveService.addLove(love);
            if (i > 0) {
                return ServerResponse.createBySuccessMessage("喜欢成功");
            }
        }
        return ServerResponse.createByErrorMessage("获取用户信息失败！");
    }


    /**
     * 取消喜欢
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/delLove")
    @ResponseBody
    public ServerResponse<String> delLove(@RequestBody Love myLove) {
        User user = hostHolder.getUser();
        User hostUser = hostHolder.getUser();
        if (hostUser.getUserId() == -1) {
            return ServerResponse.createBySuccessMessage("匿名用户不允许操作");
        }
        if (user != null) {
            Love love = new Love();
            love.setUnitId(myLove.getUnitId());
            love.setUserId(user.getUserId());
            int i = loveService.delLove(love);
            if (i > 0) {
                return ServerResponse.createBySuccessMessage("取消成功");
            }
        }
        return ServerResponse.createByErrorMessage("获取用户信息失败！");
    }


    /**
     * 收藏
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/addCollection")
    @ResponseBody
    public ServerResponse<String> addCollection(@RequestBody Collection collection) {
        User user = hostHolder.getUser();
        User hostUser = hostHolder.getUser();
        if (hostUser.getUserId() == -1) {
            return ServerResponse.createBySuccessMessage("匿名用户不允许操作");
        }
        if (user != null && collection.getUnitId() != null) {
            collection.setUserId(user.getUserId());
            collection.setCreateTime(new Date());
            int i = collectionService.addCollection(collection);
            if (i > 0) {
                return ServerResponse.createBySuccessMessage("收藏成功");
            }
        }
        return ServerResponse.createByErrorMessage("获取用户信息失败！");
    }

    /**
     * 取消收藏
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/unCollection")
    @ResponseBody
    public ServerResponse<String> unCollection(@RequestBody Collection collection) {
        User user = hostHolder.getUser();
        User hostUser = hostHolder.getUser();
        if (hostUser.getUserId() == -1) {
            return ServerResponse.createBySuccessMessage("匿名用户不允许操作");
        }
        if (user != null && collection.getUnitId() != null) {
            collection.setUserId(user.getUserId());
            int i = collectionService.delCollection(collection);
            if (i > 0) {
                return ServerResponse.createBySuccessMessage("取消成功");
            }
        }
        return ServerResponse.createByErrorMessage("获取用户信息失败！");
    }

    /**
     * 获取收藏列表
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/myCollection")
    @ResponseBody
    public ServerResponse<List<Collection>> myCollection(@RequestParam("userId") int userId) {
        List<Collection> myCollection = collectionService.getMyCollection(userId);
        return ServerResponse.createBySuccess(myCollection);
    }

}